<template>
  <div>
    <BreadCrumbShow :pageTitle="pageTitle" />
    <!-- <PendingTips
      :tips="false"
      :title="'此申请仅由窍楚永久下架，自行永久下架需求请联系客服。'"
    ></PendingTips> -->

    <!-- <PageTitle pageTitle="永久下架" /> -->

    <PendingTips
      v-if="!isClosePending && tempBoxListNum > 0"
      @close="toClosePending"
      :title="'您的临时列表中有'"
      :num="tempBoxListNum"
      @goToTemplist="goToTemplist"
    ></PendingTips>

    <Division v-if="!isClosePending && tempBoxListNum > 0" />

    <div class="search-list">
      <el-form
        :inline="true"
        :model="searchForm"
        class="form-inline"
        @submit.native.prevent
      >
        <el-form-item>
          <el-input
            size="medium"
            placeholder="请输入标签或窍编号进行搜索（多个关键字用空格分开）"
            v-model="searchForm.keyword"
            class="input-with-select"
            clearable
            @keyup.enter.native="
              () => {
                pageNum = 1;
                getUserBoxList();
              }
            "
          >
            <!-- <i class="el-icon-search" slot="prepend"></i> -->
            <el-button
              slot="append"
              type="primary"
              @click="
                () => {
                  pageNum = 1;
                  getUserBoxList();
                }
              "
              >搜索窍</el-button
            >
          </el-input>
        </el-form-item>
      </el-form>
    </div>
    <div class="keyword-search" v-if="keywordList.length > 0">
      <div class="label">已选条件:</div>
      <div class="tag-show">
        <el-tag
          v-for="tag in keywordList"
          :key="tag"
          closable
          @close="closeKeyword(tag)"
          size="medium"
        >
          {{ tag }}
        </el-tag>
      </div>
    </div>

    <div class="apply-operate">
      <div class="left">
        <el-button
          :disabled="applyNum == 0"
          type="primary"
          size="small"
          @click="applyRead"
          >申请永久下架({{ applyNum }})</el-button
        >
        <el-button
          v-if="isPrivateLocal"
          size="small"
          :disabled="applyNum == 0"
          @click="addDestroyListBefore"
          >加入下架列表({{ applyNum }})</el-button
        >
        <el-button
          v-else
          size="small"
          :disabled="applyNum == 0"
          @click="addDestroyList"
          >加入下架列表({{ applyNum }})</el-button
        >
        <el-button size="small" @click="batchImportApply"
          >批量导入下架窍</el-button
        >
      </div>

      <div class="right">
        <el-button size="mini" @click="goLog">
          <div class="btn">
            <span class="text">永久下架记录</span>
          </div>
        </el-button>
        <el-button size="small" @click="goApprove" v-if="showApprove">
          <div class="btn">
            <span class="text">去下架审批界面</span>
          </div>
        </el-button>
      </div>
    </div>

    <ElTable
      refName="applyOffshelfList"
      @select="selectHandle"
      @pageChange="pageChange"
      @selectionChange="selectionChange"
      :type="2"
      :data-source="userBoxList"
      :data-config="tableConfig"
      :total="total"
      :pageSize="pageSize"
      :pageNum="pageNum"
      :isLoading="isLoading"
    >
      <template #boxCodeHeader>
        <div class="header-select">
          <el-select
            v-model="boxCodeHeader"
            placeholder="窍类别"
            size="medium"
            @change="changeSelect"
            clearable
          >
            <el-option
              v-for="item in tableConfig.filter((e) => e.prop == 'boxCode')[0]
                .selectOption"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            ></el-option>
          </el-select>
        </div>
      </template>
      <template #boxCode="{ scope }">
        <BoxIconShow :rowInfo="scope.row" />
      </template>
      <template #boxTag="{ scope }">
        <div class="cell-tag">
          <span v-for="(tags, index) in scope.row.boxTagList" :key="index">
            <el-tag
              v-if="index <= 5 && tags.tag.length <= 15"
              class="box-tag mr-5"
              type="info"
              size="small"
              @click="toClickTag(tags)"
            >
              {{ tags.tag }}
            </el-tag>
            <el-tooltip
              class="item"
              effect="light"
              :content="tags.tag"
              placement="top"
            >
              <el-tag
                v-if="index <= 5 && tags.tag.length > 15"
                class="box-tag mr-5"
                type="info"
                size="small"
                @click="toClickTag(tags)"
              >
                {{ tags.tag.substring(0, 15) + "..." }}
              </el-tag>
            </el-tooltip>
          </span>
          <el-tag
            type="info"
            size="small"
            class="box-tag"
            @click="goBoxDetail(scope.row)"
            v-if="scope.row.boxTagList && scope.row.boxTagList.length > 6"
            >......</el-tag
          >
        </div>
      </template>
      <template #rackCode="{ scope }">
        <!-- 只有是档案窍存在云窍箱子中 才会有 云窍号-index  去点击查询 -->
        <span @click="showNext(scope.row)" class="hand statusOrange" v-if="scope.row.boxType == 5 && scope.row.userBoxSubBean && scope.row.userBoxSubBean.mainBoxCode">{{scope.row.userBoxSubBean.mainBoxCode }}-{{ scope.row.userBoxSubBean.index}}</span>
        <span v-else>{{scope.row.rackCode && scope.row.rackCode.code}}</span>
      </template>
      <template #operate="{ scope }">
        <el-button size="mini" @click.native="goBoxDetail(scope.row)" :class="boxCodeList.includes(scope.row.boxCode)?'click-ago': ''"
          >详情</el-button
        >
      </template>
      <template #bottom-btn>
        <el-button
          :disabled="applyNum == 0"
          type="primary"
          size="small"
          @click="applyRead"
          >申请永久下架({{ applyNum }})</el-button
        >
      </template>
    </ElTable>

    <!-- 批量导入永久下架 -->
    <ImportReadDialog
      title="批量导入永久下架"
      :isImportRead="isImportRead"
      @submitImport="submitImport"
      @modeUpload="modeUpload"
      @closeImportDialog="closeDialog"
    />

    <!-- 申请永久下架弹框 -->
    <ApplyOffshelfDialog
      :isApplyDestroy="isApplyDestroy"
      :userInfo="userInfo"
      :selectedList="selectedList"
      @closeApplyDialog="closeDialog"
      @getList="getUserBoxList"
    />

    <!-- 展示云窍下的档案窍 -->
    <ShowNextBox
      :isShowNextBox.sync="isShowNextBox"
      @closeDialog="closeDialog"
      :showRow="showRow"
      :userBoxList='userBoxList'
    />
  </div>
</template>

<script>
import PendingTips from "../../components/PendingTips";
import Division from "../../components/Division";
import ElTable from "@/components/table/ElTable.vue";
import ImportReadDialog from "../access-manage/components/ImportReadDialog";
import ApplyOffshelfDialog from "./components/ApplyOffshelfDialog";
import BoxIconShow from "@/components/public-style/BoxIconShow";
import PageTitle from "@/components/PageTitle";
import ShowNextBox from "@/views/access-manage/components/ShowNextBox.vue";
import {
  getUserBoxList,
  getUserBoxListCount,
  getUserBoxListByTag,
  // getTaglistByUserBoxId,
  getTaglistByUserBoxIds,
  toImportTemp,
  toAddTemp,
  getTempBoxListNum,
} from "../../api/access-manage/index";
import {
  encryption,
  applySubType,
  clarityType,
} from "../../utils/dictionary.js";
import Cookies from "js-cookie";

export default {
  name: "applyOffshelfList",
  components: {
    PendingTips,
    Division,
    ElTable,
    ImportReadDialog,
    ApplyOffshelfDialog,
    BoxIconShow,
    PageTitle,
    ShowNextBox
  },
  data() {
    return {
      isPrivateLocal: process.env.VUE_APP_LOCAL == 'huaian',
      boxCodeHeader: '',
      boxCodeList: [],
      userInfo: {},
      encryption: encryption,
      applySubType: applySubType,
      clarityType: clarityType,
      pageTitle: "申请下架列表",
      userBoxList: [],
      tableConfig: [
        {
          label: "类别 | 编号",
          prop: "boxCode",
          width: "350",
          selectOption: [
            { label: "云窍 ", value: "2" },
            { label: "档案窍 ", value: "5" },
          ],
        },
        {
          prop: "boxTag",
          label: "标签",
          width: "450",
          showTooltip: false,
        },
        {
          prop: "rackCode",
          label: "货位",
        },
        {
          prop: "bindedOn",
          label: "绑定时间",
        },
        {
          prop: "operate",
          label: "操作",
          width: 100,
        },
      ],
      isLoading: false,
      total: 0,
      pageSize: 10,
      pageNum: 1,
      searchForm: {
        keyword: "",
      },
      keywordList: [],

      isImportRead: false,
      isApplyDestroy: false,

      isClosePending: false,

      uploadFile: {},
      tempBoxListNum: 0,
      applyNum: 0,
      selectedList: [], // 选中的窍
      isShowNextBox: false,
      showRow: {},
      showApprove: false,
      tagTwo: false
    };
  },
  created() {
    const currentStorage = JSON.parse(localStorage.getItem("localUserInfo"))
    let authIdArr = currentStorage && currentStorage.authIdArr || []
    this.showApprove = authIdArr.includes(1060200);
  },
  mounted() {
    this.userInfo = JSON.parse(Cookies.get("userInfo"));
    if (this.$route.query.tag) {
      this.keywordList = [this.$route.query.tag];
    }

    this.getUserBoxList();
    this.getTempBoxNum();
    this.boxCodeList = []
  },
  methods: {
    // 点击档案窍的云窍窍号，展示它下级所有的档案窍
    showNext(row) {
      this.showRow = row
      // 打开弹窗展示
      this.isShowNextBox = true
    },
    // 去下架记录
    goLog() {
      this.$router.push({
        path: "/offshelf/log",
      });
    },
    // 去下架审批界面
    goApprove() {
      this.$router.push({
        path: '/offshelf/approve'
      })
    },
    // 点击标签 去搜索
    toClickTag(tags) {
      // 将tag 添加到 keywordList
      this.keywordList.push(tags.tag);
      this.keywordList = [...new Set(this.keywordList)];
      this.pageNum = 1;
      this.getUserBoxList();
    },
    // 获得临时窍 永久下架数目
    getTempBoxNum() {
      this.isClosePending = false;
      new Promise((resolve) => {
        getTempBoxListNum(3).then((res) => {
          this.tempBoxListNum = res.data;
        });
      });
    },
    // 分页数据变动
    pageChange(emitData) {
      this.pageNum = emitData.pageNum;
      this.pageSize = emitData.pageSize;
      this.getUserBoxList();
    },
    // 选择项变化
    selectionChange(selectArr) {
      this.applyNum = selectArr.length;
      this.selectedList = selectArr;
    },

    // 头部筛选项变化
    changeSelect() {
      this.pageNum = 1;
      this.getUserBoxList();
    },
    // 将keyword 添加到keywordList中 , 清空 searchForm
    addKeyword() {
      if (this.searchForm.keyword && this.searchForm.keyword != "") {
        const tagList = this.searchForm.keyword
          .split(" ")
          .filter((e) => e !== "");

        this.keywordList = [...new Set(this.keywordList.concat(tagList))];
        this.searchForm.keyword = "";
      }
    },
    // 删除 已有的keyword
    closeKeyword(tag) {
      this.keywordList.splice(this.keywordList.indexOf(tag), 1);
      this.pageNum = 1;
      this.getUserBoxList();
    },
    // 窍列表 -- 联动窍标签查询   ---- 后查询到的id一起下架
    getUserBoxListByTag(userBoxIdList) {
      const data = {
        userBoxIdList: userBoxIdList,
        subFlag: 0,
        type: 3
      }

      getUserBoxListByTag(data, {}).then(res => {
        console.log(res, res.data, '=======')
        // 更改 selectedList 的内容
        if (res.code == 200) {
          this.selectedList = this.selectedList.concat(res.data)
          this.addDestroyList()
        }
      })

    },
    // 获得用户窍列表
    getUserBoxList() {
      this.addKeyword();
      // type 0调阅 1回库 2销毁 3永久下架
      const data = {
        type: 3,
        keywordList: this.keywordList, // 多个关键字
        boxType: this.boxCodeHeader ? this.boxCodeHeader : null,
        subFlag: 0, // 0 返回 档案窍及云窍   1  返回 容器窍
      };

      const params = {
        pageSize: this.pageSize,
        pageNum: this.pageNum,
      };
      this.isLoading = true;
      this.userBoxList = [];
      getUserBoxListCount(data, params).then(res => {
        this.total = res.data;
      })
      new Promise((resolve) => {
        getUserBoxList(data, params)
          .then((res) => {
            res.data.map((e) => {
              e.bindedOn = this.$moment(e.bindedOn * 1000).format(
                "YYYY-MM-DD HH:mm:ss"
              );
            });
            this.userBoxList = res.data;

            // this.total = res.total;
            // this.userBoxList.map((item) => {
            //   getTaglistByUserBoxId({ userBoxId: item.id }).then((tagRes) => {
            //     item["boxTagList"] = tagRes.data;
            //     this.$forceUpdate();
            //   });
            // });
            if (this.userBoxList.length > 0) {
              let ids = [];
              this.userBoxList.map((item) => {
                ids.push(item.userBoxId);
              });

              getTaglistByUserBoxIds(ids).then((res) => {
                this.userBoxList.map((item) => {
                  res.data.map((tags) => {
                    if (tags.userBoxId == item.userBoxId) {
                      item["boxTagList"] = tags.tagList.filter(m => m.tag != ';' && m.tag != '；');
                      item["xdTagType"] = tags.xdTagType;
                      // 1 - 消贷一级 2-消贷二级
                      this.$forceUpdate();
                    }
                  });
                });
              });
            }

            this.isLoading = false;
          })
          .catch((err) => {
            this.isLoading = false;
          });
      });
    },
    // 点击多选框 选中
    selectHandle(a) {},

    // 关闭临时列表 提示
    toClosePending(data) {
      this.isClosePending = data;
    },
    // 去 窍详情
    goBoxDetail(row) {
      // 点击过的详情的颜色变
      this.boxCodeList.push(row.boxCode)
      // this.$router.push({
      //   // name: "BoxDetail",
      //   name: 'OffshelfBoxDetail',
      //   params: {
      //     id: row.userBoxId,
      //   },
      // });
      let routeUrl = this.$router.resolve({
        name: "OffshelfBoxDetail",
        params: { id: row.userBoxId },
      });
      window.open(routeUrl.href, "_blank");
    },
    // 加入永久下架列表, 如果有二级消贷，则提示是否将一级消贷加入下架列表
    addDestroyListBefore() {
      console.log('this.selectedList', this.selectedList)
      // 循环窍的标签，有 消贷二级的 则 弹框提示
      this.tagTwo = false
      // this.selectedList.map(e => {
      //   if (e.boxTagList.filter(m => m.tag == '消贷二级').length > 0) {
      //     this.tagTwo = true
      //   }
      // })
      if (this.selectedList.filter(m => m.xdTagType == 2).length > 0) {
        this.tagTwo = true
      }
      if (this.tagTwo) {
        // 循环窍的标签，有 消贷二级的 则 弹框提示
        this.$confirm("您所选的窍中有二级消贷，是否将其所属一级消贷加入永久下架列表?", "提示", {
          confirmButtonText: "加入",
          cancelButtonText: "不加入",
          type: "warning",
        }).then(res => {
          this.getUserBoxListByTag(this.selectedList.map(e => e.userBoxId))
        }).catch(() => {
          this.addDestroyList()
        })
      } else {
        this.addDestroyList()
      }
    },
    // 加入永久下架列表
    addDestroyList() {
      let userBoxIdList = [];
      this.selectedList.map((e) => {
        userBoxIdList.push(e.userBoxId);
      });

      new Promise((resolve) => {
        // 0调阅 1回库 2销毁 3永久下架
        toAddTemp(userBoxIdList, { type: 3 }).then((res) => {
          if (res.code == 200) {
            this.commonFun.getTempReturnInfo(res.data, this);
            this.getTempBoxNum();
          }
        });
      });
    },
    // 出现 导入调阅弹窗
    batchImportApply() {
      this.isImportRead = true;
    },
    // 申请调阅
    applyRead() {
      this.isApplyDestroy = true;

      // // 循环窍的标签，有 消贷二级的 则 弹框提示
      // this.tagTwo = false
      // this.selectedList.map(e => {
      //   if (e.boxTagList.filter(m => m.tag == '消贷二级').length > 0) {
      //     this.tagTwo = true
      //   }
      // })
      // if (this.tagTwo) {
      //   this.getUserBoxListByTag(this.selectedList.map(e => e.userBoxId))
      // }
    },

    // 关闭 弹框
    closeDialog() {
      this.isApplyDestroy = false;
      this.isImportRead = false;
    },
    // 上传文件
    modeUpload(param) {
      // this.$refs.uploadButton.clearFiles();
      this.uploadFile = param;
    },
    // 批量导入永久下架 - 确认
    submitImport() {
      if (!this.uploadFile.file) {
        this.$message({
          type: "error",
          message: "请选择文件后上传",
        });
        return;
      }

      let formData = new FormData();
      formData.append("file", this.uploadFile.file);
      // this.$refs.uploadButton.submit();
      // this.$refs.uploadButton.clearFiles();
      toImportTemp(formData, { type: 3 })
        .then((res) => {
          if (res.code == 200) {
            this.commonFun.getTempReturnInfo(res.data, this);
            this.isImportRead = false;
            // this.getUserBoxList();
            this.goToTemplist(); // 跳转至临时列表
          }
        })
        .catch((err) => {
          this.isLoading = false;
        });
    },
    // 去临时列表
    goToTemplist() {
      this.$router.push({
        name: "OffshelfTempList",
        params: { type: 3 },
      });
    },
  },
};
</script>

<style lang="scss" scoped>
.box-code {
  display: flex;
  align-items: center;
  .el-image-box {
    height: 70px;
    width: 90px;
    margin-right: 10px;
    text-align: center;
    .el-image {
      height: 100%;
    }
  }

  .title {
    color: #333;
    font-size: 12px;
    font-weight: 550;
  }
}
.img-box {
  display: flex;
  justify-content: center;
  align-items: center;

  img {
    width: 70%;
  }
}
</style>

<style lang="scss" scoped>
.search-list {
  // margin-bottom: 15px;
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding-top: 20px;
  ::v-deep .el-form {
    flex: 1;
  }
  .form-inline {
    ::v-deep .el-form-item {
      margin-bottom: 0;
      width: 100%;
    }
    ::v-deep  .el-form-item__content {
      width: 40%;
    }

    ::v-deep  .el-input-group__append {
      color: #fff;
      background-color: #f88123;
    }
  }
}
.keyword-search {
  display: flex;
  // justify-content: center;
  align-items: center;
  margin-bottom: 20px;
  .label {
    min-width: 50px;
    margin-right: 10px;
    font-size: 10px;
    margin-top: 3px;
  }
  .tag-show {
    flex-wrap: wrap;
    ::v-deep  .el-tag {
      margin: 5px 10px 5px 0;
    }
  }
}

.apply-read-dialog {
  .dialog-title {
    color: #f88123;
    font-size: 16px;
  }
  .more-box-show {
    background: #eee;
    color: #f88123;
    padding-left: 10px;
  }
  .show-more {
    cursor: pointer;
  }
}
.page {
  margin-bottom: 30px;
}
.apply-operate {
  margin-top: 10px;
  margin-bottom: 15px;
  display: flex;
  justify-content: space-between;
  align-items: center;
  .right {
    .btn {
      font-weight: bolder;
    }
  }
}

// 列表中的tag
.cell-tag {
  .box-tag {
    margin-bottom: 5px;
    cursor: pointer;

    .box-tag-span {
      width: 40px;
      overflow: hidden;
    }
  }
}
</style>
<style lang="scss">
.el-select {
  ::v-deep .el-select__tags {
    // 解决多个tag卡片溢出隐藏问题
    overflow: hidden;
    display: -webkit-box;
    -webkit-line-clamp: 1;
    -webkit-box-orient: vertical;

    .el-tag {
      // 注意这个inline-block 对卡片溢出隐藏很重要
      display: inline-block;

      // 解决单个tag文字过长溢出隐藏问题
      .el-select__tags-text {
        display: inline-block;
        max-width: 70px;
        overflow: hidden;
        text-overflow: ellipsis;
        white-space: nowrap;
      }

      .el-icon-close {
        top: -6px;
        right: -4px;
      }
    }
  }
}

.el-input-group__prepend {
  background-color: transparent;
}

.click-ago {
  background: rgba(255, 139, 49, 0.2);
}
</style>
